package com.sicheng.lc.杂题.多路归并技巧之构造有序链表;

import com.sicheng.algorithm.node.ListNode;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * @author zsc
 * @version 1.0
 * @date 2022/7/15 22:33
 */
public class 合并K个升序链表 {
    //https://leetcode.cn/problems/merge-k-sorted-lists/

    static ListNode t = new ListNode(-1);

    {
        t.next = null;
    }

    public ListNode mergeKLists(ListNode[] lists) {

        if (lists.length == 0)
            return null;
        PriorityQueue<ListNode> heap = new PriorityQueue<>(Comparator.comparingInt(k -> k.val));
        for (ListNode list : lists) {
            if (list != null)
                heap.offer(list);
        }


        ListNode h = t;
        while (!heap.isEmpty()) {
            ListNode p = heap.poll();
            h.next = p;
            h = p;
            if (p.next != null) {
                p = p.next;
                heap.offer(p);
            }
        }
        return t.next;
    }
}
